﻿using System;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using NotAClue.ComponentModel.DataAnnotations;
using NotAClue.Web.DynamicData;
using NotAClue;
using System.Text;

namespace DD_Extensions
{
    public partial class CascadeHierarchicalField : System.Web.DynamicData.FieldTemplateUserControl
    {
        // default allow navigation
        private bool _allowNavigation = true;
        // value to use to separate values in the Hierarchy
        private const string DISPLAY_SEPERATOR = " > ";
        public string NavigateUrl { get; set; }

        public bool AllowNavigation
        {
            get { return _allowNavigation; }
            set { _allowNavigation = value; }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            // add tool-tip
            this.SetupTip();

            // add CSS from meta data
            this.ApplyCss();

            //var pageTemplate = Page.GetPageTemplate();
            //var disableNavigationInAttribute = GetDisableNavigationInAttribute();
            //if (disableNavigationInAttribute != null && (disableNavigationInAttribute.PageTemplate & pageTemplate) == pageTemplate)
            if (this.IsNavigationDisabled(Column))
                HyperLink1.Enabled = false;
        }

        //private DisableNavigationInAttribute GetDisableNavigationInAttribute()
        //{
        //    DisableNavigationInAttribute disableNavigationInAttribute;

        //    // get table version of attribute
        //    disableNavigationInAttribute = ForeignKeyColumn.ParentTable.GetAttribute<DisableNavigationInAttribute>();

        //    if (disableNavigationInAttribute != null)
        //        return disableNavigationInAttribute;

        //    // get column version of attribute
        //    disableNavigationInAttribute = ForeignKeyColumn.GetAttribute<DisableNavigationInAttribute>();

        //    if (disableNavigationInAttribute != null)
        //        return disableNavigationInAttribute;

        //    return null;
        //}

        protected String GetDisplayString()
        {
            // make sure this is a navigation property (ForeignKey column navigation property)
            if (!(Column is MetaForeignKeyColumn))
                throw new InvalidOperationException(String.Format("Column {0} must be a foreign key column navigation property", Column.Name));

            // get cascade hierarchical attribute
            var cascadeHierarchicalAttribute = Column.GetAttribute<CascadeHierarchicalAttribute>();
            if (cascadeHierarchicalAttribute == null)
                throw new InvalidOperationException("Was expecting a CascadeFilterAttribute.");

            // check for null value
            if (FieldValue != null)
            {
                //get parent table
                var parentTable = ForeignKeyColumn.ParentTable;

                // add this foreign key navigation property to the sorted list
                var fieldValues = new SortedList<int, String>();
                fieldValues.Add(0, ForeignKeyColumn.ParentTable.GetDisplayString(FieldValue));

                // get current value as an object
                Object currentValue = FieldValue;

                // loop through each navigation property to build values
                for (int i = 0; i < cascadeHierarchicalAttribute.Parameters.Length; i++)
                {
                    // set name of parent column
                    var parentColumnName = cascadeHierarchicalAttribute.Parameters[i];

                    // get parent column from name
                    var parentColumn = (MetaForeignKeyColumn)parentTable.GetColumn(parentColumnName);

                    // check for valid column
                    if (parentColumn == null && !(parentColumn is MetaForeignKeyColumn))
                        throw new InvalidOperationException(String.Format("Invalid parent column {0}", parentColumnName));

                    // get next value
                    currentValue = currentValue.GetPropertyValue(parentColumnName);

                    // extract current value as string using the parent table's display string
                    var currentValueString = FormatFieldValue(parentColumn.ParentTable.GetDisplayString(currentValue));

                    // add current value as string to the sorted field values list
                    fieldValues.Add(i + 1, currentValueString);

                    // set next parent table
                    parentTable = parentColumn.ParentTable;
                }

                // build display string
                var displayString = new StringBuilder();
                for (int i = cascadeHierarchicalAttribute.Parameters.Length; i >= 0; i--)
                    displayString.Append(fieldValues[i] + DISPLAY_SEPERATOR);

                // return the built string
                return FormatFieldValue(displayString.ToString().Substring(0, displayString.ToString().Length - 2));
            }
            else
                // same as standard foreign key field
                return FormatFieldValue(ForeignKeyColumn.ParentTable.GetDisplayString(FieldValue));
        }

        protected string GetNavigateUrl()
        {
            if (!AllowNavigation)
                return null;

            if (String.IsNullOrEmpty(NavigateUrl))
                return ForeignKeyPath;
            else
                return BuildForeignKeyPath(NavigateUrl);
        }

        public override Control DataControl
        {
            get { return HyperLink1; }
        }
    }
}
